var comPageNum = 1;
getSpecialTypeId();

function getSpecialTypeId() {
    $.ajax({
        url: root.goodsInter.goods_getSpecialSkuTypes,
        cache: false, //禁用缓存
        type: "POST",
        success: function (data) {
            if (data.errorCode == 0) {
                var specialSkuTypesHtml = '<option value="" selected>不限</option><option value="-1">正常商品</option>';
                for (var i = 0; i < data.data.length; i++) {
                    specialSkuTypesHtml += '<option value="' + data.data[i].id + '">' + data.data[i].name + '</option>';
                }
                $(".specialTypeId").html(specialSkuTypesHtml);
            }
        }
    });
}

var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];

function skuListShelf(data) {
    dataSource.splice(0, dataSource.length);//清空数组
    $.each(data.data.list, function (i, field) {
        var rowData = new Array();
        rowData.push(field.sku_code);
        rowData.push(field.sale_attri_value);
        rowData.push(field.unit_name);
        rowData.push(field.parts_number);
        rowData.push(field.yc_sales_stauts);
        var date = new Date(field.last_shelf_on_time);
        Y = date.getFullYear() + '-';
        M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        D = (date.getDate() < 10 ? '0'+(date.getDate()) : date.getDate()) + ' ';
        h = (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours()) + ':';
        m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()): date.getMinutes())+ ':';
        s = date.getSeconds()< 10 ? '0'+(date.getSeconds()) : date.getSeconds();
        rowData.push(Y+M+D+h+m+s);
        rowData.push(field.distribution_price);
        rowData.push(field.sku_id);
        rowData.push(field.product_code);
        rowData.push(field.lable_floor);
        rowData.push(field.sku_name);
        rowData.push(field.specification_properties);
        rowData.push(field.color);
        var date = new Date(field.creation_date);
        Y = date.getFullYear() + '-';
        M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        D = (date.getDate() < 10 ? '0'+(date.getDate()) : date.getDate()) + ' ';
        h = (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours()) + ':';
        m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()): date.getMinutes())+ ':';
        s = date.getSeconds()< 10 ? '0'+(date.getSeconds()) : date.getSeconds();

        rowData.push(Y+M+D+h+m+s);
        rowData.push(field.spu_id);

        // 商品尺寸
        rowData.push(field.max_length); // 15
        rowData.push(field.sub_length); // 16
        rowData.push(field.volume);     // 17
        rowData.push(field.weight);     // 18
        rowData.push(field.price);      // 19
        rowData.push(field.distribution_price);      // 20
        rowData.push(field.actual_stock);            // 21
        rowData.push(field.virtual_stock);           // 22
        rowData.push(field.pro_useable);             // 23
        rowData.push(field.specialTypeName);
        rowData.push(field.order_limit_type);
        rowData.push(field.yc_mini_order);
        rowData.push(field.shelf_operation_source);//上下架来源


        dataSource.push(rowData);
    });
    initDataTable(dataSource);

    function initDataTable(dataSource) {
        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            "order": [[ 8, "desc" ]],
            "autoWidth": false,
            "ordering": true,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": [5, 10, 25, 50],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
                "sProcessing": "<img src='./loading.gif' />"
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function(data,type,row,meta){
                        var val = '<span><input class="skuId" type="checkbox" name="skuId" value = "'+ row[7] +'">Code码：'+row[0]+'</span>';
                        return val;
                    },
                    "targets": 0
                },
                {
                    /*属性*/
                    "render": function(data,type,row,meta){
                        if (row[11] == null){
                            row[11] = '';
                        }
                        var val = '<span>' +row[11]+ '</span>';
                        return val;
                    },
                    "targets": 1
                },
                {
                    /*件装数量*/
                    "render": function(data,type,row,meta){
                        if(row[3] == null ){
                            row[3]  = '';
                        }
                        var val = '<span>' +row[3]+ '</span>';
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = ""
                        if (row[25] == 0) {
                            val = '起售量整数倍'
                        }else if (row[25] == 1) {
                            val = '不低于起售量'
                        }
                        return val;
                    },
                    "targets": 3
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[26]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 4
                },


                {
                    /*创建时间*/
                    "render": function(data,type,row,meta){
                        var val = '<span>' +row[13]+ '</span>';
                        return val;
                    },
                    "targets": 5
                },
                {
                    /*上架时间*/
                    "render": function(data,type,row,meta){
                        if(row[5] == null ){
                            row[5]  = '';
                        }
                        var val = '<span>' +row[5]+ '</span>';
                        return val;
                    },
                    "targets": 6
                },
                {
                    /*上下架操作*/
                    "render": function (data, type, row, meta) {
                        var shelf_operation_source=""//上下架来源
                        if(row[27]==10){
                            shelf_operation_source=""
                        }else if(row[27]==15){
                            shelf_operation_source=""
                        }else if(row[27]==20){
                            shelf_operation_source="商品下架"
                        }else if(row[27]==25){
                            shelf_operation_source="运营下架"
                        }
                        if (row[4] == 0 || row[4] == null) {
                            var val = '<span class="dropDown"> <a class="dropDown_A powerButton 428" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">未上架<i class="Hui-iconfont">&#xe6df;</i></a><ul class="dropDown-menu menu radius box-shadow"><li onclick="sku_start(\'\',\'' + row[7] + '\')"><a href="#">上架</a></li></ul><br><span>'+shelf_operation_source+'</span></span>';
                            return val;
                        } else if (row[4] == 1) {
                            var val = '<span class="dropDown"> <a class="dropDown_A powerButton 428" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">已上架<i class="Hui-iconfont">&#xe6df;</i></a><ul class="dropDown-menu menu radius box-shadow"><li onclick="sku_end(\'\',\'' + row[7] + '\')"><a href="#">下架</a></li></ul><br><span>'+shelf_operation_source+'</span></span>';
                            return val;
                        } else if (row[4] == 2) {
                            var val = '<span class="dropDown"> <a class="dropDown_A powerButton 428" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">已下架<i class="Hui-iconfont">&#xe6df;</i></a><ul class="dropDown-menu menu radius box-shadow"><li onclick="sku_start(\'\',\'' + row[7] + '\')"><a href="#">上架</a></li></ul><br><span>'+shelf_operation_source+'</span></span>';
                            return val;
                        }
                    },
                    "targets": 7
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '<a><span class="list powerButton 429" onclick="goods_check(\'Code详情\',\'sku-info.html\',\''+row[7]+'\')">查看详情</span></a>';/*<br/><span class="list powerButton 431" onclick="goProduct(\'预览详情\',\'product.html\',\''+row[14]+'\')">商品预览</span>*/
                        return val;
                    },
                    "targets": 8
                }
            ],
            "fnInitComplete": function(oSettings, json) {
                setBtnDis(0,$("#productSkuManage"));
                $("#datatable").on("click",'.skuId',function(){
                    var num = $(".shun").find("input[type=checkbox]:checked").length;
                    setBtnDis(num,$("#productSkuManage"));
                });

            }
        });
        power();
    };
}
function sku_cha(pageNum) {
    comPageNum = pageNum;
    $.ajax({
        contentType: 'application/json',
        url: root.goodsInter.goods_getSkuList,
        cache: false,  //禁用缓存
        type: "POST",
        data: JSON.stringify({
            pageSize: 50,
            nowPage: pageNum,
            model: {
                spuId: sessionStorage.getItem("spuId"),
                skuCode:      $("#productCode").val(),
                startTime:    $("#timemin").val(),
                endTime:      $("#timemax").val(),
                specifications: $("#saleAttriValue").val(),
                creatTime:    $("#creatimemin").val(),
                creatEndTime: $("#creatimemax").val(),
               /* areaId:   sessionStorage.getItem("areaId"),*/
            }//传入组装的参数
        }),
        success: function (data) {
           /* if(data.data.list.length==0&&comPageNum!=1){
                sku_cha(comPageNum-1);
                return;
            }*/
            skuListShelf(data);
            $("#spu_all").attr("checked",false);
            if(data.data.list=="" || data.data.list==null){
                totalPage = 0
            }else {
                totalPage = data.data.totalPage;
            }

            $('.M-box4').pagination({
                pageCount: totalPage,
                current: comPageNum,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function(api) {
                    comPageNum = api.getCurrent();
                    sku_cha(api.getCurrent());
                }
            });
        }
    });
}
/*表单验证特殊字符*/
function ValidateValue(textbox) {
    var IllegalString = "[`~!#$^&*()=|{}':;',\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？]‘’";
    var textboxvalue = textbox.value;
    var index = textboxvalue.length - 1;
    var s = textbox.value.charAt(index);
    if (IllegalString.indexOf(s) >= 0) {
        s = textboxvalue.substring(0, index);
        textbox.value = s;
        layer.msg("不能输入特殊字符");
    }
}

/*tab切换*/
jQuery.Huitab = function (tabBar, tabCon, class_name, tabEvent, i) {
    var $tab_menu = $(tabBar);
// 初始化操作
    $tab_menu.removeClass(class_name);
    $(tabBar).eq(i).addClass(class_name);
    $(tabCon).hide();
    $(tabCon).eq(i).show();
    $tab_menu.bind(tabEvent, function () {
        $tab_menu.removeClass(class_name);
        $(this).addClass(class_name);
        var index = $tab_menu.index(this);
        $(tabCon).hide();
        $(tabCon).eq(index).show()
    })
}
//获取用户信息
var localStorageParameters = decodeURIComponent(web.readCookie("loginData"));
var JsonObject =JSON.parse(localStorageParameters);
//上架
function sku_start(obj, id) {
    console.log(id);
    layer.confirm('确认要上架吗？', function (index) {
        var spu_data = {
            spuId: sessionStorage.getItem("spuId"),
            ids: id,
            status: 1,
            lastModifiedBy:JsonObject.user.user_ID,
            lastModifiedName:JsonObject.user.name,
            operateSource:15//云采上架
        }
        var succCallBack = function (data, status, response) {
            if (data.errorCode == 0) {
                var message=""
                if(data.notAllowOperateSkus!=""){
                    message=data.notAllowOperateSkus[0].message
                }
                layer.msg("上架成功有"+data.allowOperateSkus.length+"个商品,上架失败有"+data.notAllowOperateSkus.length +"个商品!"+'<br>'+message, {icon: 6, time: 3000}, function () {
                    sku_cha(comPageNum);
                });
            } else {
                layer.msg(data.errorMessage, {icon: 6, time: 3000}, function () {
                    sku_cha(comPageNum);
                });
            }
        };
        return web.doAjax(root.goodsInter.goods_setSKUSaleStatus, 'post', spu_data, succCallBack);
    });
}

//下架
function sku_end(obj, id) {
    console.log(id);
    layer.confirm('确认要下架吗？', function (index) {
        var spu_data = {
            spuId: sessionStorage.getItem("spuId"),
            ids: id,
            status: 2,
            lastModifiedBy:JsonObject.user.user_ID,
            lastModifiedName:JsonObject.user.name,
            operateSource:25//云采下架
        }
        var succCallBack = function (data, status, response) {

            if (data.errorCode == 0) {
                var message=""
                if(data.notAllowOperateSkus!=""){
                    message=data.notAllowOperateSkus[0].message
                }
                layer.msg("下架成功有"+data.allowOperateSkus.length+"个商品,下架失败有"+data.notAllowOperateSkus.length +"个商品!"+'<br>'+message, {icon: 6, time: 3000}, function () {
                    sku_cha(comPageNum);
                });
            } else {
                layer.msg(data.errorMessage, {icon: 6, time: 3000}, function () {
                    sku_cha(comPageNum);
                });
            }
        };
        return web.doAjax(root.goodsInter.goods_setSKUSaleStatus, 'post', spu_data, succCallBack);
    });
}

var allIds = "";//批量上下架的id
function stopProp() {
    /*批量上架全选框阻止冒泡*/
    var timer = setTimeout(function(){
        var num = $("#datatable").find("tbody").find("input[type=checkbox]:checked").length;
        setBtnDis(num,$("#productSkuManage"));
        clearTimeout(timer);
    },200)
    window.event? window.event.cancelBubble = true : e.stopPropagation();
}
//批量上架
function sku_up(obj) {
    layer.confirm('确认要批量上架吗？', function (index) {
        allIds = document.getElementsByClassName('skuId');
        var ids = [];
        for(var i=0;i<allIds.length;i++){
            console.log(allIds[i].checked)
            if(allIds[i].checked == true){
                ids.push(allIds[i]);
            }
        }
        var idStr = "";
        for (var i = 0; i < ids.length; i++) {
            idStr += ids[i].value + ","
        }
        idStr = idStr.substring(0, idStr.length - 1);
        var spu_data = {
            spuId: sessionStorage.getItem("spuId"),
            ids: idStr,
            status: 1,
            lastModifiedBy:JsonObject.user.user_ID,
            lastModifiedName:JsonObject.user.name,
            operateSource:15//云采上架

        }
        var succCallBack = function (data, status, response) {
            if (data.errorCode == 0) {
                layer.msg("上架成功有"+data.allowOperateSkus.length+"个商品,上架失败有"+data.notAllowOperateSkus.length +"个商品!", {icon: 6, time: 3000}, function () {
                    sku_cha(comPageNum);
                });
            } else {
                layer.msg(data.errorMessage, {icon: 6, time: 3000}, function () {
                    sku_cha(comPageNum);
                });
            }
        };
        return web.doAjax(root.goodsInter.goods_setSKUSaleStatus, 'post', spu_data, succCallBack);
    });
}

//批量下架
function sku_down(obj) {
    layer.confirm('确认要批量下架吗？', function (index) {
        allIds = document.getElementsByClassName('skuId');
        var ids = [];
        for(var i=0;i<allIds.length;i++){
            console.log(allIds[i].checked)
            if(allIds[i].checked == true){
                ids.push(allIds[i]);
            }
        }
        var idStr = "";
        for (var i = 0; i < ids.length; i++) {
            idStr += ids[i].value + ","
        }
        idStr = idStr.substring(0, idStr.length - 1);
        var spu_data = {
            spuId: sessionStorage.getItem("spuId"),
            ids: idStr,
            status: 2,
            lastModifiedBy:JsonObject.user.user_ID,
            lastModifiedName:JsonObject.user.name,
            operateSource:25//云采下架
        }
        var succCallBack = function (data, status, response) {
            if (data.errorCode == 0) {
                layer.msg("下架成功有"+data.allowOperateSkus.length+"个商品,下架失败有"+data.notAllowOperateSkus.length +"个商品!", {icon: 6, time: 3000}, function () {
                    sku_cha(comPageNum);
                });
            } else {
                layer.msg(data.errorMessage, {icon: 6, time: 3000}, function () {
                    sku_cha(comPageNum);
                });
            }
        };
        return web.doAjax(root.goodsInter.goods_setSKUSaleStatus, 'post', spu_data, succCallBack);
    });
}


/*sku信息列表*/
function goods_check(title,url,sku_Id) {
    sessionStorage.removeItem("scene_lable");
    sessionStorage.removeItem("skuInfo");
    sessionStorage.removeItem("mini_order");
    sessionStorage.removeItem("order_limit_type");
    sessionStorage.removeItem("skuImgCache");
    sessionStorage.removeItem("attrObjCanch");
    var index = layer.open({
        type: 2,
        title: title,
        content: url +'?sku_Id='+sku_Id
    });
    layer.full(index);
}
function goods_stock(title,url,sku_Id) {
    var index = layer.open({
        type: 2,
        title: title,
        content: url+'?sku_Id='+sku_Id
    });
    layer.full(index);
}

function goProduct (title,url,spu_Id) {
    var index = layer.open({
        type: 2,
        title: title,
        content: url+'?spu_Id='+spu_Id
    });
    layer.full(index);
}
function setBtnDis(num,pnode){  //如果选中项为空时，置灰相关按钮
    if(num<=0){
        pnode.find(".goods_edit").attr("disabled","disabled").addClass("dis_btn");
    }else{
        pnode.find(".goods_edit").removeAttr("disabled").removeClass("dis_btn");
    }
}
function spuNameCache() {
    var spuCode = "SPU码：" + sessionStorage.getItem("spuCode");
    var spuName = "商品名称：" + sessionStorage.getItem("spuName");
    var areaId = sessionStorage.getItem("areaId");
    var areaName;
    var warehouses=JSON.parse(sessionStorage.getItem("warehouses"))
    for(var i=0;i<warehouses.data.length;i++){
        if(Number(areaId)==warehouses.data[i].belongAreaId){
            areaName = '区域：'+warehouses.data[i].warehouseAliasName+'';
        }

    }
    document.getElementById("spuId_title").innerHTML = spuCode;
    document.getElementById("spuName_title").innerHTML = spuName;
    /*document.getElementById("spuId_sale_area").innerHTML = areaName;*/
    //sessionStorage.removeItem("spuCode");
    //sessionStorage.removeItem("spuName");
}